﻿using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.Project.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class ProjectStatusChangeRecordRepository : Repository<ProjectStatusChangeRecord, DefaultDbContext>
    {
        public ProjectStatusChangeRecordRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
        }

        public IEnumerable<ProjectStatusChangeRecord> GetProjectStatusChangeRecordsByProjectId(int projectId)
        {
            int areaVersion = EntityCacheService.GetAreaVersion("ProjectId", projectId);
            return GetTopEntities(1000, CachingExpirationType.ObjectCollection, () =>
            {
                return $"ProjectStatusChangeRecordsByProjectId:{projectId}:{areaVersion}";
            }, () =>
            {
                Sql sql = Sql.Builder
                .Select("id")
                .From("project_status_change_record")
                .Where("project_id=@0", projectId);
                return sql;
            });
        }

        public IEnumerable<ProjectStatusChangeRecord> GetProjectStatusChangeRecordsByProjectIds(IEnumerable<int> projectIds)
        {
            if (projectIds == null || projectIds.Count() == 0)
                return Enumerable.Empty<ProjectStatusChangeRecord>();

            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("project_status_change_record")
                .Where("project_id IN(@0)", projectIds);
            var ids = DbContext.FetchFirstColumn<int>(sql);
            return PopulateEntitiesByEntityIds(ids);
        }
    }
}